import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Dialog, DialogTitle, DialogContent, Button, FormControlLabel, Switch  } from '@mui/material';
import "./Feeding.css"

const AddSensorDialog = ({ open, onClose, fetchData }) => {
    const [sensorName, setSensorName] = useState("");
    const [location, setLocation] = useState("");
    const [minOperatingCondition, setMinOperatingCondition] = useState('');
    const [maxOperatingCondition, setMaxOperatingCondition] = useState("");
    const [minCriticalCondition, setMinCriticalCondition] = useState('');
    const [maxCriticalCondition, setMaxCriticalCondition] = useState('');
    const [minFatalCondition, setMinFatalCondition] = useState('');
    const [maxFatalCondition, setMaxFatalCondition] = useState('');
    const [units, setUnits] = useState("");
    const [frequency, setFrequency] = useState("");
    const [onOff, setOnOff] = useState(false);
    const [equipmentId, setEquipmentId] = useState("");
    const [equipments, setEquipments] = useState([]);
    const [dimension, setDimension] = useState("");
    const [comment, setComment] = useState("");



    useEffect(() => {
        fetchEquipments();
    }, []);

    const fetchEquipments = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/equipment`, {headers});
            setEquipments(response.data.equipments);
        } catch (error) {
            console.error('Error fetching equipments:', error);
        }
    };

    const addSensor = async () => {
        try {
            const newSensor = {
                "name": sensorName,
                "location": location,
                "min_operating_condition": minOperatingCondition,
                "max_operating_condition": maxOperatingCondition,
                "min_critical_condition": minCriticalCondition,
                "max_critical_condition": maxCriticalCondition,
                "min_fatal_condition": minFatalCondition,
                "max_fatal_condition": maxFatalCondition,
                "units": units,
                "frequency": frequency,
                "on_off": onOff,
                "id_equipment": equipmentId, 
                "dimension": dimension
            }
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            await axios.post(`${process.env.REACT_APP_API_BASE_URL}/sensors`, newSensor, {headers});
            fetchData();
            onClose();
        } catch (error) {
            console.error('Error adding new sensor:', error);
        }
    };

    const handleInputChange = (setter) => (event) => {
        setter(event.target.value);
    };

    const handleNumberInputChange = (setter) => (event) => {
        const value = parseFloat(event.target.value);
        setter(isNaN(value) ? 0 : value);
    };

    const handleCheckboxChange = (event) => {
        setOnOff(event.target.checked);
    };

    return (
        <Dialog open={open} onClose={onClose} sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none' } }}>
            <DialogTitle>Добавить новые данные о датчике</DialogTitle>
            <DialogContent>
                <div>
                    <div className='input-table-container'>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Наименование датчика</label>
                            <input
                                type="text"
                                value={sensorName}
                                onChange={handleInputChange(setSensorName)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Местоположение</label>
                            <input
                                type="text"
                                value={location}
                                onChange={handleInputChange(setLocation)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Оборудование</label>
                            <select
                                value={equipmentId}
                                onChange={handleInputChange(setEquipmentId)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                <option>Выберите оборудование</option>
                                {equipments.map(equipment => (
                                    <option key={equipment.eid} value={equipment.eid}>{equipment.ename}</option>
                                ))}
                            </select>
                            </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Единицы измерения</label>
                            <input
                                type="text"
                                value={units}
                                onChange={handleInputChange(setUnits)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                       <label>Частота</label>
                            <select
                                value={frequency}
                                onChange={handleInputChange(setFrequency)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                               {[1,2,3,4,5,6,7,8,9,10].map((i) => (<option value={i} >{i} раз</option>))}
                                
                            </select>
                            <label>Размерность</label>
                            <select
                                value={dimension}
                                onChange={handleInputChange(setDimension)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                               <option value={1}>В час</option>
                               <option value={2}>В день</option>
                               <option value={3}>В неделю</option>
                               <option value={4}>В месяц</option>
                               <option value={5}>В год</option>
                            </select>
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Минимальное рабочее состояние</label>
                            <input
                                type="number"
                                value={minOperatingCondition}
                                onChange={handleNumberInputChange(setMinOperatingCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                            <label>Максимальное рабочее состояние</label>
                            <input
                                type="number"
                                value={maxOperatingCondition}
                                onChange={handleNumberInputChange(setMaxOperatingCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Минимальное критическое состояние</label>
                            <input
                                type="number"
                                value={minCriticalCondition}
                                onChange={handleNumberInputChange(setMinCriticalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                            <label>Максимальное критическое состояние</label>
                            <input
                                type="number"
                                value={maxCriticalCondition}
                                onChange={handleNumberInputChange(setMaxCriticalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Минимальное фатальное состояние</label>
                            <input
                                type="number"
                                value={minFatalCondition}
                                onChange={handleNumberInputChange(setMinFatalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                            <label>Максимальное фатальное состояние</label>
                            <input
                                type="number"
                                value={maxFatalCondition}
                                onChange={handleNumberInputChange(setMaxFatalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       </div>
                       
                            <div style={{ display: 'grid', gridTemplateColumns: "1.55fr 0.5fr 1fr", gap: '200px 20px' }}>
                            <FormControlLabel
                                control={
                                    <Switch
                                        checked={onOff}
                                        onChange={() => {setOnOff(!onOff)}}
                                    />
                                }
                                label={onOff? "Датчик включен":"Датчик выключен"}
                                sx={{ marginLeft:1,
                                    '& .MuiFormControlLabel-label': {
                                        fontFamily: 'Montserrat', fontWeight: 'bolder',
                                    }
                                }}
                            />
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: "0.2fr 1fr", gap: '10px' }}>
                            <label>Комментарий</label>
                            <textarea
                                className='input-form-table'
                                type="text"
                                value={comment}
                                onChange={handleInputChange(setComment)}
                                style={{ borderColor: '#003AD0', margin: 0, width: '90%', maxWidth: '1400px' }}
                                required={true}
                            />
                        </div>
                            <Button disabled={!(location && (location.length >= 5))} onClick={addSensor} variant="contained"
                                                        sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }}
                                                        >
                                Сохранить
                            </Button>
                        </div>
                </div>
            </DialogContent>
        </Dialog>
    );
};

export default AddSensorDialog;
